package com.concurrent.demo;

import java.util.concurrent.locks.StampedLock;

/**
 * @Date 2020/7/9 17:40
 * @Author admin
 * @Description
 */
public class StampedLockDemo {
    final StampedLock sl = new StampedLock();
    //读模板
    void read(){
        //读入方法局部变量
//        乐观读
        long stamp = sl.tryOptimisticRead();
        //校验stamp
        if(!sl.validate(stamp)){
            //升级为悲观读锁
            sl.readLock();
            try{
                //读入方法局部变量
            }finally {
                //释放悲观读锁
                sl.unlockRead(stamp);
            }
        }
        //使用方法局部变量执行业务操作
    }

    //写模板
    void write(){
        long stamp = sl.writeLock();
        try {
            //写共享变量
        }finally {
            sl.unlockWrite(stamp);
        }
    }

}
